package com.doge.walknovel.analysis

import android.app.Activity
import android.os.Bundle
import com.appsflyer.AFInAppEventParameterName
import com.appsflyer.AFInAppEventType
import com.appsflyer.AppsFlyerLib
import com.doge.walknovel.business.login.PROFILE_TYPE_FACEBOOK
import com.doge.walknovel.business.login.PROFILE_TYPE_GOOGLE
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.utils.appContext
import com.doge.walknovel.utils.log
import com.doge.walknovel.utils.runOnIO
import com.facebook.appevents.AppEventsConstants
import com.facebook.appevents.AppEventsLogger
import com.google.firebase.analytics.FirebaseAnalytics
import com.tendcloud.tenddata.TCAgent
import com.tendcloud.tenddata.TDProfile
import java.math.BigDecimal
import java.util.*

private val afLogger by lazy { AppsFlyerLib.getInstance() }
private val fbLogger by lazy { AppEventsLogger.newLogger(appContext) }
private val firebaseLogger by lazy { FirebaseAnalytics.getInstance(appContext) }

fun analysisInitUser(userId: Int = AccountHelper.self.memberId) = runOnIO {
    if (userId > 0) {
        afLogger.setCustomerUserId(userId.toString())
        AppEventsLogger.setUserID(userId.toString())
        firebaseLogger.setUserId(userId.toString())
    }
}

fun Activity.analysisOnPageStart() =
    runOnIO { TCAgent.onPageStart(this, this.javaClass.simpleName) }

fun Activity.analysisOnPageEnd() = runOnIO { TCAgent.onPageEnd(this, this.javaClass.simpleName) }

fun analysisEvent(eventId: String) = runOnIO {
    afLogger.logEvent(appContext, eventId, null)
    fbLogger.logEvent(eventId)
    firebaseLogger.logEvent(eventId, null)
    TCAgent.onEvent(appContext, eventId)
    log("analysisEvent $eventId")
}

/** 有收入的应用内购买事件 */
fun analysisPurchase(productId: String, orderId: String, orderType: String, currency: String?, revenue: String?, priceAmountMicros: Long) = runOnIO {
    if (currency == null || revenue == null) return@runOnIO

    val appsFlyersEventValue = mapOf(
        AFInAppEventParameterName.ORDER_ID to orderId,
        AFInAppEventParameterName.CONTENT_ID to productId,
        AFInAppEventParameterName.CONTENT_TYPE to orderType,
        AFInAppEventParameterName.CURRENCY to currency,
        AFInAppEventParameterName.REVENUE to revenue
    )
    afLogger.logEvent(appContext, AFInAppEventType.PURCHASE, appsFlyersEventValue)

    val realPriceValue: Double = (priceAmountMicros.toDouble() / 1000000)
    val params = Bundle()
    params.putString("fb_order_id", orderId)
    params.putString("fb_content_id", productId)
    params.putString("fb_content_type", orderType)
    params.putString("fb_currency", currency)
    params.putString("fb_revenue", realPriceValue.toString())
    fbLogger.logPurchase(BigDecimal(realPriceValue), Currency.getInstance(currency), params)

    firebaseLogger.logEvent(AFInAppEventType.PURCHASE, params)

    TCAgent.onOrderPaySucc(
        orderId,
        (realPriceValue * 100).toInt(),
        currency,
        orderType
    )

    log("analysisEvent Purchase currency $currency revenue $revenue orderId $orderId productId $productId realPriceValue $realPriceValue")
}

fun analysisLogin(profileType: Int) = runOnIO {
    val t = when (profileType) { // 1 facebook 2 google
        PROFILE_TYPE_FACEBOOK -> TDProfile.ProfileType.TYPE1
        PROFILE_TYPE_GOOGLE -> TDProfile.ProfileType.TYPE2
        else -> TDProfile.ProfileType.TYPE10
    }

    afLogger
        .logEvent(appContext, AFInAppEventType.LOGIN, mapOf("ProfileType" to t.index()))

    val params = Bundle()
    params.putString("ProfileType", t.index().toString())
    fbLogger.logEvent(AFInAppEventType.LOGIN, params)
    firebaseLogger.logEvent(AFInAppEventType.LOGIN, params)
    TCAgent.onLogin("", t, "")
}

fun analysisRegister(profileType: Int) = runOnIO {
    val t = when (profileType) { // 1 facebook 2 google
        PROFILE_TYPE_FACEBOOK -> TDProfile.ProfileType.TYPE1
        PROFILE_TYPE_GOOGLE -> TDProfile.ProfileType.TYPE2
        else -> TDProfile.ProfileType.TYPE10
    }

    afLogger
        .logEvent(
            appContext,
            AFInAppEventType.COMPLETE_REGISTRATION,
            mapOf("ProfileType" to t.index())
        )

    val params = Bundle()
    params.putString("ProfileType", t.index().toString())

    fbLogger.logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION, params)
    firebaseLogger.logEvent(AFInAppEventType.COMPLETE_REGISTRATION, params)
    TCAgent.onRegister("", t, "")
}

fun analysisAppOpened() = runOnIO {
    afLogger.logEvent(appContext, "af_app_opened", null)
    fbLogger.logEvent(AppEventsConstants.EVENT_NAME_ACTIVATED_APP)
    firebaseLogger.logEvent("af_app_opened", null)
    TCAgent.onEvent(appContext, "af_app_opened")
}

/** 点击通知 */
fun analysisPushClicked(type: String?) = runOnIO {
    afLogger
        .logEvent(
            appContext,
            AFInAppEventType.OPENED_FROM_PUSH_NOTIFICATION,
            mapOf("type" to (type ?: ""))
        )

    val params = Bundle()
    params.putString("type", type ?: "")

    fbLogger.logEvent(AFInAppEventType.OPENED_FROM_PUSH_NOTIFICATION, params)
    firebaseLogger.logEvent(AFInAppEventType.OPENED_FROM_PUSH_NOTIFICATION, params)
    TCAgent.onEvent(appContext, AFInAppEventType.OPENED_FROM_PUSH_NOTIFICATION, type ?: "")
}